package cn.dankal.flyaudio;

import android.content.ContentResolver;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.StringUtils;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.DrawableRes;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import api.ShopUserServiceFactory;
import byc.imagewatcher.ImageWatcher;
import byc.imagewatcher.ImageWatcherHelper;
import cn.dankal.basiclib.base.fragment.BaseFragment;
import cn.dankal.basiclib.pojo.BaseResponse;
import cn.dankal.basiclib.pojo.CarouselListEntity;
import cn.dankal.basiclib.pojo.CategoryListEntity;
import cn.dankal.basiclib.pojo.ProductEntity;
import cn.dankal.basiclib.pojo.ShopCarEntity;
import cn.dankal.basiclib.pojo.StoreHomeEntity;
import cn.dankal.basiclib.pojo.req.AddShopCarReq;
import cn.dankal.basiclib.rx.AbstractSubscriber;
import cn.dankal.basiclib.util.ActivityUtils;
import cn.dankal.basiclib.util.AppUtils;
import cn.dankal.basiclib.util.DisplayHelper;
import cn.dankal.basiclib.util.SharePreferenceManager;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.basiclib.widget.banner.DkBanner;
import cn.dankal.basiclib.widget.banner.IViewHolder;
import cn.dankal.basiclib.widget.banner.OnBannerItemClickListener;
import cn.dankal.basiclib.widget.banner.VH;
import cn.dankal.basiclib.widget.swipetoloadlayout.OnRefreshListener;
import cn.dankal.basiclib.widget.swipetoloadlayout.SwipeToLoadLayout;
import cn.dankal.flyaudio.adapter.StoreMenuAdapter;
import cn.dankal.flyaudio.adapter.StoreProductAdapter;
import cn.dankal.flyaudio.current.post.BannerItemView;
import cn.dankal.flyaudio.friend.utils.takevideo.utils.LogUtils;
import cn.dankal.flyaudio.pop.AddShopCarPop;
import cn.dankal.flyaudio.store.ClassificationActivity;
import cn.dankal.flyaudio.store.GlideSimpleLoader;
import cn.dankal.flyaudio.store.SearchActivity;
import cn.dankal.flyaudio.store.ShoppingCarActivity;
import cn.dankal.flyaudio.store.WebViewActivity;

public class StoreFragment extends BaseFragment implements View.OnClickListener {

    private RecyclerView menuView;

    private RecyclerView newProductView;

    private RecyclerView hotProductView;

    private StoreMenuAdapter adapter;

    private StoreProductAdapter newProductAdapter;

    private StoreProductAdapter hotProductAdapter;
    private ImageWatcherHelper iwHelper;//方式二
    SwipeToLoadLayout mSwipeToLoadLayout;


    private TextView searchView;
    private List<ProductEntity> products = new ArrayList<>();
    private List<CarouselListEntity> carouselListEntities = new ArrayList<>();
    private DkBanner dkBanner;
    private TextView numText;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_store;
    }

    @Override
    protected void initComponents() {
        numText = getView().findViewById(R.id.tv_system_public_number);
        menuView = getView().findViewById(R.id.rv_menu);
        newProductView = getView().findViewById(R.id.rv_new_tuijian);
        hotProductView = getView().findViewById(R.id.rv_hot_tuijian);
        searchView = getView().findViewById(R.id.et_search);
        mSwipeToLoadLayout = getView().findViewById(R.id.swipe_toload_layout);
        mSwipeToLoadLayout.setRefreshEnabled(true);
        mSwipeToLoadLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                initData();
            }
        });
        dkBanner = getView().findViewById(R.id.dk_banner);
        // 如果不是透明状态栏，你需要给ImageWatcher标记 一个偏移值，以修正点击ImageView查看的启动动画的Y轴起点的不正确
        ImageWatcherHelper.with(getActivity(), new GlideSimpleLoader())
                .setErrorImageRes(R.mipmap.error_picture) // 配置error图标 如果不介意使用lib自带的图标，并不一定要调用这个API
                .setOnStateChangedListener(new ImageWatcher.OnStateChangedListener() {
                    @Override
                    public void onStateChangeUpdate(ImageWatcher imageWatcher, ImageView clicked, int position, Uri uri, float animatedValue, int actionTag) {
                        Log.e("IW", "onStateChangeUpdate [" + position + "][" + uri + "][" + animatedValue + "][" + actionTag + "]");
                    }

                    @Override
                    public void onStateChanged(ImageWatcher imageWatcher, int position, Uri uri, int actionTag) {
                        if (actionTag == ImageWatcher.STATE_ENTER_DISPLAYING) {
//                            Toast.makeText(getApplicationContext(), "点击了图片 [" + position + "]" + uri + "", Toast.LENGTH_SHORT).show();
                        } else if (actionTag == ImageWatcher.STATE_EXIT_HIDING) {
//                            Toast.makeText(getApplicationContext(), "退出了查看大图", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

        adapter = new StoreMenuAdapter();
        newProductAdapter = new StoreProductAdapter();
        hotProductAdapter = new StoreProductAdapter();
        newProductAdapter.setType("0");
        hotProductAdapter.setType("0");
        newProductView.setLayoutManager(new GridLayoutManager(getContext(), 2));
        hotProductView.setLayoutManager(new GridLayoutManager(getContext(), 2));
        menuView.setLayoutManager(new GridLayoutManager(getContext(), 4));
        menuView.setAdapter(adapter);
        newProductView.setAdapter(newProductAdapter);
        hotProductView.setAdapter(hotProductAdapter);
        newProductAdapter.addDatas(products, true);
        hotProductAdapter.addDatas(products, true);
        searchView.setOnClickListener(this);
        getView().findViewById(R.id.rl_hot_tuijian).setOnClickListener(this);
        getView().findViewById(R.id.iv_shopping_car).setOnClickListener(this);
        getView().findViewById(R.id.rl_new_tuijian).setOnClickListener(this);
        initData();

        LiveEventBus.get("StoreProductJoin", ProductEntity.class)
                .observe(this, new Observer<ProductEntity>() {
                    @Override
                    public void onChanged(ProductEntity s) {
                        //加入购物车
                        searchSku(s.getUuid());
                    }
                });
        LiveEventBus.get("ShopCarNum",String.class).observe(this,
                new Observer<String>() {
                    @Override
                    public void onChanged(String s) {
                        getMyShopCar();
                    }
                });
        getMyShopCar();
    }

    public void getMyShopCar() {
        ShopUserServiceFactory.mySHopCar()
                .subscribe(new AbstractSubscriber<BaseResponse<List<ShopCarEntity>>>(this) {
                    @Override
                    public void onNext(BaseResponse<List<ShopCarEntity>> listBaseResponse) {
                        if(listBaseResponse.getData().size()>0) {
                            numText.setVisibility(View.VISIBLE);
                            int size = listBaseResponse.getData().size();
                            if(size>99){
                                numText.setText("99");
                            }else{
                                numText.setText(String.valueOf(size));
                            }

                        }else{
                            numText.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

    private AddShopCarPop addShopCarPop;

    public void searchSku(String productUuid) {
        showLoadingDialog();
        ShopUserServiceFactory.shopDetail(productUuid)
                .subscribe(new AbstractSubscriber<BaseResponse<ProductEntity>>(this) {
                    @Override
                    public void onNext(BaseResponse<ProductEntity> productEntityBaseResponse) {
                        dismissLoadingDialog();
                        ProductEntity entity = productEntityBaseResponse.getData();
                        if (entity.getItems() == null || entity.getItems().isEmpty()) {
                            addShopCar("-1", 1);
                            return;
                        }
                        if (entity.getItems().size() == 1) {
                            addShopCar(entity.getItems().get(0).getUuid(), 1);
                            return;
                        }
                        if (addShopCarPop == null) {
                            addShopCarPop =
                                    new AddShopCarPop(getContext()).setAddShopListener(new AddShopCarPop.AddShopCarListener() {
                                        @Override
                                        public void doAdd(int num, String itemUuid, String desc) {
                                            if (android.text.TextUtils.isEmpty(itemUuid)) {
                                                ToastUtils.showShort("没有库存!");
                                                return;
                                            }
                                            addShopCar(itemUuid, num);
                                        }

                                        @Override
                                        public void doBuy(int num, String itemUuid, String itemDesc) {

                                        }
                                    });
                        }
                        LogUtils.e(addShopCarPop.isShowing() + "-----");
                        if (!addShopCarPop.isShowing()) {
                            addShopCarPop.setShop(productEntityBaseResponse.getData()).showPopupWindow(0, 2000);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        dismissLoadingDialog();
                    }
                });
    }

    public void addShopCar(String productUuid, int count) {
        showLoadingDialog();
        AddShopCarReq req = new AddShopCarReq();
        req.setItemUuid(productUuid);
        req.setItemCount(count + "");
        ShopUserServiceFactory.addShopCar(req)
                .subscribe(new AbstractSubscriber<BaseResponse<Object>>(this) {
                    @Override
                    public void onNext(BaseResponse<Object> productEntityBaseResponse) {
                        dismissLoadingDialog();
                        getMyShopCar();
                        ToastUtils.showShort("加入购物车成功");
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        dismissLoadingDialog();
                    }
                });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (R.id.iv_shopping_car == id) {
            ActivityUtils.startActivity(ShoppingCarActivity.class);
        } else if (R.id.et_search == id) {
            ActivityUtils.startActivity(SearchActivity.class);
        } else if (R.id.rl_hot_tuijian == id || R.id.rl_new_tuijian == id) {
            Intent intent = new Intent(ActivityUtils.getTopActivity(), ClassificationActivity.class);
            intent.putExtra("category_uuid", "");
            ActivityUtils.startActivity(intent);
        }
    }

    private String getResourcesUri(@DrawableRes int id) {
        Resources resources = getResources();
        String uriPath = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
                resources.getResourcePackageName(id) + "/" +
                resources.getResourceTypeName(id) + "/" +
                resources.getResourceEntryName(id);
        return uriPath;
    }

    private void initData() {
        ShopUserServiceFactory.storeHome()
                .subscribe(new AbstractSubscriber<BaseResponse<StoreHomeEntity>>(this) {
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        mSwipeToLoadLayout.setRefreshing(false);
                    }

                    @Override
                    public void onNext(BaseResponse<StoreHomeEntity> storeHomeEntityBaseResponse) {
                        mSwipeToLoadLayout.setRefreshing(false);
                        List<CategoryListEntity> categoryListEntities = storeHomeEntityBaseResponse.getData().getCategoryList();
                        SharePreferenceManager.setCachedStoreCategory(storeHomeEntityBaseResponse.getData().getCategoryList());
                        CategoryListEntity categoryListEntity = new CategoryListEntity();
                        categoryListEntity.setName("更多");
                        carouselListEntities =
                                storeHomeEntityBaseResponse.getData().getCarouselList();

                        initBanner(storeHomeEntityBaseResponse.getData().getCarouselList());
                        categoryListEntity.setImgUrl(getResourcesUri(R.mipmap.youpin_ic_more));
                        if (categoryListEntities.size() > 7) {
                            adapter.addDatas(categoryListEntities.subList(0, 7), true);
                        } else {
                            adapter.addDatas(categoryListEntities, true);
                        }
                        adapter.addData(categoryListEntity);
                        newProductAdapter.addDatas(storeHomeEntityBaseResponse.getData().getNewProductList(), true);
                        hotProductAdapter.addDatas(storeHomeEntityBaseResponse.getData().getHotProductList(), true);
                    }
                });
    }


    private void initBanner(List<CarouselListEntity> bannerDate) {
        List<String> data = new ArrayList<>();
        for (CarouselListEntity carouselListEntity : carouselListEntities) {
            data.add(carouselListEntity.getImgUrl());
        }
        dkBanner.setIndicatorPoint(R.drawable.oval_indicator, R.drawable.oval_indicator_unselect,
                DisplayHelper.dp2px(AppUtils.getApp(), 10), DisplayHelper.dp2px(AppUtils.getApp(), 10));
        dkBanner.setOnItemClickListener(new OnBannerItemClickListener() {
            @Override
            public void onItemClick(View view, Object o, int postion, int realPostion) {
                List<Uri> uris = new ArrayList<>();
                Uri uri = Uri.parse(o.toString());
                if (StringUtils.isEmpty(bannerDate.get(postion).getTargetUrl())) {
                    return;
                }
                Intent intent = new Intent(ActivityUtils.getTopActivity(), WebViewActivity.class);
                intent.putExtra("url", bannerDate.get(postion).getTargetUrl());
                startActivity(intent);
//                ARouter.getInstance().build(NORMAL_WEBVIEW)
//                        .withString("title", "系統消息")
//                        .withString("url", bannerDate.get(postion).getTargetUrl())
//                        .withString("uuid", "")
//                        .navigation();
//                uris.add(uri);
//                iwHelper.show(uris, 0);
            }
        });
        dkBanner.setVpAdapter(data, new IViewHolder<String>() {
            @Override
            public VH<String> create() {
                return new BannerItemView();
            }
        });

    }
}
